//
//  EcgMeasureVc.m
//  CareRingApp
//
//  Created by Linktop on 2024/3/6.
//

#import "EcgMeasureVc.h"
#import <QMUIKit/QMUIKit.h>
#import <Masonry/Masonry.h>
#import "UIViewController+Custom.h"
#import "ConfigModel.h"
#import "LTRingEcgDrawLineView.h"
#import "LTHmEcgGridView.h"
#import "DeviceCenter.h"
#import "EcgNoTouchTipView.h"
#import "AppDelegate.h"
#import "SymptomsBtnView.h"

#import "ImgTitleItem.h"
#import "LTRingEcgDrawHistoryView.h"
#import "SepLineView.h"


@interface EcgMeasureVc ()<SRBleScanProtocal, SRBleDataProtocal>
@property(strong, nonatomic)QMUIButton *startBtn, *doneBtn;
@property(strong, nonatomic)UILabel *topLabel, *hrDescLbl, *resTipLbl, *chargeTipLbl;

@property(strong, nonatomic)UIImageView *hrImageView;
@property(strong, nonatomic) ImgTitleItem *hrItem;

@property(strong, nonatomic)LTRingEcgDrawLineView *realMeaDrawLineView;
@property(strong, nonatomic) LTHmEcgGridView *realGridView;

@property(strong, nonatomic) LTRingEcgDrawHistoryView *hisDrawLineView; // 测量结束全览图

@property(strong, nonatomic)NSArray <NSDictionary *>* xspeedArray, *yGainArray;
@property(assign, nonatomic) HORIZONTAL_SPEED xSpeed;
@property(assign, nonatomic) VERTIAL_GAIN yGain;

@property(weak, nonatomic)EcgNoTouchTipView *noTouchTipView;


@property(strong, nonatomic)NSMutableArray<SrEcgAlgorithmResults *> *ecgResultArray;

@property(assign, nonatomic)BOOL measuring;

@property(strong, nonatomic) DBEcgRecord *ecgRecord;

@property(assign, nonatomic) ECG_MEA_STA state;  // 界面显示状态机

@property(strong, nonatomic) UIButton *infoBtn;


@property(strong, nonatomic)UIScrollView *scrollView;
@property(strong, nonatomic) UIView *mainContent;
@property(assign, nonatomic) ECG_WEAR_HAND wearHand;

@property(strong, nonatomic) UISegmentedControl *handSegment;


@end

@implementation EcgMeasureVc

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initConstData];
    [self initUI];
    
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [DeviceCenter instance].appDataDelegate = self;
    [DeviceCenter instance].sRappScanDelegate = self;
    
    BOOL isconnected = [DeviceCenter instance].isBleConnected;
    self.startBtn.enabled = isconnected;
    
    if (self.state == ECG_MEA_STA_INIT) {
        self.state = ECG_MEA_STA_INIT;
    }
    [UIApplication sharedApplication].idleTimerDisabled = YES; // 常亮

    if (self.state == ECG_MEA_STA_INIT && [DeviceCenter instance].isCharging) {
        self.chargeTipLbl.hidden = NO;
    } else {
        self.chargeTipLbl.hidden = YES;
    }

}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self stopEcgMeasure]; //离开关闭测量
    [UIApplication sharedApplication].idleTimerDisabled = NO; // 关闭常亮

}

- (void)initConstData {
    self.wearHand = LEFT_HAND;
    _xspeedArray = @[@{@"title" : @"25mm/s", @"idx" : @(HORIZONTAL_SPEED_DEFAULT)},
                    @{@"title" : @"50mm/s", @"idx" : @(HORIZONTAL_SPEED_DOUBLE)},
    ];
    _yGainArray = @[@{@"title" : @"5 mm/mv", @"idx" : @(VERTIAL_GAIN_HALF)},
                    @{@"title" : @"10 mm/mv", @"idx" : @(VERTIAL_GAIN_DEFAULT)},
                    @{@"title" : @"20 mm/mv", @"idx" : @(VERTIAL_GAIN_DOUBLE)},
    ];
    
    self.xSpeed = HORIZONTAL_SPEED_DEFAULT;
    self.yGain = VERTIAL_GAIN_DEFAULT;
}

-(void)initUI {
    
    self.navigationItem.title = _L(L_NAV_TITLE_ECG_MEASURMENT);
    WEAK_SELF
    [self arrowback:^{
        STRONG_SELF
        [strongSelf stopEcgMeasure];// 停止测量
        [strongSelf.navigationController popViewControllerAnimated:YES];
    }];
    
    [self.view addSubview:self.scrollView];
    
    [self.scrollView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
    }];
    
    self.mainContent = [UIView new];
    [self.scrollView addSubview:self.mainContent];
    [self.mainContent mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mainContent.superview);
        make.centerX.equalTo(self.mainContent.superview.mas_centerX);
        make.width.equalTo(self.mainContent.superview.mas_width);
    }];
    
    [self.mainContent addSubview:self.handSegment];
    
    [self.handSegment mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.handSegment.superview.mas_centerX);
        make.top.equalTo(self.handSegment.superview.mas_safeAreaLayoutGuideTop).offset(20);
        make.height.equalTo(@40);
        
    }];

    
    self.topLabel = [UILabel new];
    self.topLabel.textAlignment = NSTextAlignmentLeft;
    [self.mainContent addSubview:self.topLabel];
    
    [self.mainContent addSubview:self.infoBtn];
   

    UIView *topCnt = [UIView new];
    [self.mainContent addSubview:topCnt];
    [self.mainContent addSubview:self.startBtn];
    
    [self.topLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(topCnt.mas_leading);
        make.height.equalTo(@44);
        make.top.equalTo(self.handSegment.mas_bottom).offset(10);
    }];
    
    [self.infoBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
      
        make.trailing.equalTo(topCnt.mas_trailing);
        make.centerY.equalTo(self.topLabel.mas_centerY);
        
    }];

    CGFloat  cntHeight = [self.hisDrawLineView.gridView lengthBySquareCount:5* 6];
    
    [topCnt mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(topCnt.superview.mas_leading).offset(10);
        make.trailing.equalTo(topCnt.superview.mas_trailing).inset(10);
        make.top.equalTo(self.topLabel.mas_bottom).offset(0);
        make.height.equalTo( @(cntHeight) );// 30个小格
    }];
    
    [topCnt layoutIfNeeded];
   
    
    // 实时
    [topCnt addSubview:self.realMeaDrawLineView];
    
    //ecg grid
    LTHmEcgGridView *gridView = [[LTHmEcgGridView alloc] init];
    [topCnt addSubview:gridView];
    self.realGridView = gridView;
    
    // 历史
    [topCnt addSubview:self.hisDrawLineView];
    
    [self.hisDrawLineView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.equalTo(self.hisDrawLineView.superview);
        
    }];
    
    CGFloat gridIntegetWidth =  [LTHmEcgGridView integetLengthFrom:topCnt.bounds.size.width];
    //layout
    [self.realMeaDrawLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.realMeaDrawLineView.superview.mas_centerX);
        
        make.width.equalTo(@(gridIntegetWidth));
//        make.bottom.equalTo(self.realMeaDrawLineView.superview.mas_bottom);
        make.height.equalTo(@(cntHeight));
        //        make.bottom.equalTo(startBtn.mas_top).offset(-3);
        make.top.equalTo(self.realMeaDrawLineView.superview.mas_top).offset(0);
    }];
    
   
    
    
    [self.realGridView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.realMeaDrawLineView.mas_centerX);
        make.centerY.equalTo(self.realMeaDrawLineView.mas_centerY);
        make.width.equalTo(self.realMeaDrawLineView.mas_width);
        make.height.equalTo(self.realMeaDrawLineView.mas_height);
    }];
    
    // 充电提示
    [self.mainContent addSubview:self.chargeTipLbl];
    [self.chargeTipLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(topCnt.mas_leading).offset(0);
        make.top.equalTo(topCnt.mas_bottom).offset(15);
        make.trailing.equalTo(topCnt.mas_trailing).inset(0);
    }];
//    UIImageView *hrView = [UIImageView new];
//    hrView.image = [UIImage imageNamed:@"ecg_hr"];
    [self.mainContent addSubview:self.hrItem];
//    self.hrImageView = hrView;
    [self.hrItem mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(topCnt.mas_leading).offset(5);
        make.top.equalTo(topCnt.mas_bottom).offset(15);
        make.trailing.equalTo(topCnt.mas_trailing).inset(5);
    }];
//    [self.view addSubview:self.heartRateLbl];
    [self.mainContent addSubview:self.hrDescLbl];
    
//    [self.heartRateLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.leading.equalTo(hrView.mas_trailing).offset(5);
//        make.centerY.equalTo(hrView.mas_centerY);
//    }];
    
    [self.hrDescLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.hrItem.mas_leading);
        make.top.equalTo(self.hrItem.mas_bottom).offset(15);
        make.trailing.equalTo(topCnt.mas_trailing).inset(5);
    }];
    
    SepLineView *sephrDesc = [self creatSepLine];
    [self.hrDescLbl.superview addSubview:sephrDesc];
    [sephrDesc mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.hrItem.mas_leading);
        make.top.equalTo(self.hrDescLbl.mas_bottom).offset(5);
        make.height.equalTo(@1);
    }];
    
   
    [self.mainContent addSubview:self.resTipLbl];
    [self.resTipLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.hrItem.mas_leading);
        make.top.equalTo(self.hrDescLbl.mas_bottom).offset(15);
        make.trailing.equalTo(topCnt.mas_trailing).inset(5);
    }];
    
    SepLineView *sepRestip = [self creatSepLine];
    sepRestip.isDash = NO;
    [self.hrDescLbl.superview addSubview:sepRestip];
    [sepRestip mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.hrItem.mas_leading);
        make.top.equalTo(self.resTipLbl.mas_bottom).offset(5);
        make.height.equalTo(@1);
    }];
    
    
   
//    [self.mainContent addSubview:self.symptomSelectView];
//    [self.symptomSelectView mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.leading.equalTo(self.hrItem.mas_leading);
//        make.trailing.equalTo(topCnt.mas_trailing).inset(5);
//        make.top.equalTo(sepRestip.mas_bottom).offset(5);
//    }];
   

    [self.startBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.height.equalTo(@44);
        make.width.equalTo(self.startBtn.superview.mas_width).multipliedBy(3.0/4);
        make.bottom.equalTo(self.startBtn.superview.mas_bottom).inset(30);
        make.top.equalTo(sepRestip.mas_bottom).offset(15);
        
    }];
    

    
    [self.mainContent addSubview:self.doneBtn];
    [self.doneBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.equalTo(self.startBtn);
    }];
    
    [self.mainContent layoutIfNeeded];
    [self.view layoutIfNeeded];
    [self.scrollView layoutIfNeeded];

    
}

-(void)startEcg:(QMUIButton *)btn {
    
//    [self showEcgUseDescView];
//    
//    return;
    
    if (!btn.isSelected) {
        // 开始测量
        [self startEcgMeasure];
        return;
    }
    
    if (btn.isSelected) {
        // 停止测量
        [self stopEcgMeasure];
        // 提前结束
        self.state = ECG_MEA_STA_INIT;
        // 显示hud
        
        return;
    }
    
//    btn.selected = !btn.isSelected;
    
}

-(void)startEcgMeasure {
    
    // 检查是否充电中
    if ([DeviceCenter instance].isCharging) {
        [self showAlertWarningWithTitle:_L(L_TIPS) Msg:_L(L_ECG_MEA_HARGE_TIP) btnOk:_L(L_SURE) OkBLk:^{
            
        } CancelBtn:nil CancelBlk:nil Compelete:nil];
        return;
    }
    
    self.ecgRecord = [[DBEcgRecord alloc]initWithMacaddress:[DeviceCenter instance].bindDevice.macAddress];
    self.ecgRecord.startTs = @((NSInteger)[NSDate date].timeIntervalSince1970);
    
    self.ecgRecord.wearHand = self.wearHand;
    
    EcgParamObj *param = [EcgParamObj defaultParam];
//    self.hmEcgDrawLineView.ecgParamObj = param;
    self.ecgResultArray = [NSMutableArray new];
//    self.volArray = [NSMutableArray new];

    self.measuring = YES;
    [[DeviceCenter instance].sdk functionECGMeasure:YES Param:param DispSrc:param.isRowWave];
    
    self.ecgRecord.firmWare = [DeviceCenter instance].bindDevice.otherInfo.fireWareVersion;
    self.ecgRecord.isRingAlgorithm = !param.isRowWave;
    
    self.state = ECG_MEA_STA_WAIT_LEADON; //进入测量中状态
    
    
//    dispatch_resume(self.timer);
}

-(void)stopEcgMeasure {
    self.measuring = NO;
    [[DeviceCenter instance].sdk functionECGMeasure:NO Param:nil DispSrc:YES];
    
//    self.startBtn.selected = NO;
//    self.startBtn.backgroundColor = MAIN_BLUE;
//    self.resTipLbl.hidden = NO;
//    self.symptomSelectView.hidden = NO;
//    self.hrImageView.hidden = NO;
    
//    [self stopTimer];
//    self.measuProgressView.hidden = YES;
    [self sumResult]; // 整理结果

    [self showResult]; // 显示结果
    
}

// 总结结果
-(void)sumResult
{
    self.ecgRecord.endTs = @((NSInteger)[NSDate date].timeIntervalSince1970);
//    DebugNSLog(@"波形数量 %lu", (unsigned long)self.ecgRecord.volArray.count);
    if (self.ecgRecord.volArray.count < 512 * (ECG_MESURING_DURA_SECONDS)) {
        DebugNSLog(@"数量不足, 波形数量 %lu", self.ecgRecord.volArray.count);

        self.ecgRecord.conclusion = CONCLUSION_NOT_ENOUGH_TIME;
        return;
    }
    
    SrEcgAlgorithmResults *lastRes = self.ecgResultArray.lastObject;
    if (lastRes) {
        [self.ecgRecord setValuesWith:lastRes];

    }

    
}

/// 显示结论信息
/// - Parameter btn:btn
-(void)gotoShowInfo:(UIButton *)btn {
 
}

-(void)showResult {

    
    if (self.ecgRecord.avgHeartRate) {
        self.hrItem.titleLbl.text = [NSString stringWithFormat:@"%@ %d%@", _L(L_AVG), self.ecgRecord.avgHeartRate.intValue, _L(L_UNIT_HR)];

    } else {
        self.hrItem.titleLbl.text = [NSString stringWithFormat:@"%@ %@%@", _L(L_AVG), NONE_VALUE, _L(L_UNIT_HR)];
    }
    
    self.topLabel.text = [DBEcgRecord titleOfConclusion:self.ecgRecord.conclusion];
    self.hrDescLbl.text = [DBEcgRecord descOfConclusion:self.ecgRecord.conclusion];
    
}

/// 弹出手指无接触提示
-(void)showEcgUseDescView {
    
    if (self.noTouchTipView) {
        return;
    }
    
    EcgNoTouchTipView *tipView = [[EcgNoTouchTipView alloc]init];
    WEAK_SELF
    tipView.closeBlk = ^{
        STRONG_SELF
        DebugNSLog(@"提示关闭");
        // 停止测量
        [strongSelf stopEcgMeasure];
        // 提前结束
        strongSelf.state = ECG_MEA_STA_INIT; // 回到初始状态
    };
    // tipView
    [((AppDelegate *)([UIApplication sharedApplication].delegate)).window addSubview:tipView];
    self.noTouchTipView = tipView;
    [tipView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.equalTo(tipView.superview);
    }];
}

-(void)hideEcgUseDescView {
    [self.noTouchTipView removeFromSuperview];
}


//-(void)showEcgChooseSymptomsView {
//    
//    if (self.chooseSymptomsView) {
//        return;
//    }
//    
//    EcgSymptomChooseView *chooseView = [[EcgSymptomChooseView alloc]init];
//    chooseView.symptoms = self.symptomSelectView.symptomsArray;
//    WEAK_SELF
//    chooseView.closeBlk = ^{
//        STRONG_SELF
//        DebugNSLog(@"提示关闭");
//    };
//    
//    chooseView.saveBlk = ^(NSMutableArray<NSNumber *> * _Nullable symptoms) {
//        STRONG_SELF
//        strongSelf.symptomSelectView.symptomsArray = symptoms;
//        strongSelf.ecgRecord.symptomsArray = symptoms;
//        
//        [strongSelf.mainContent layoutIfNeeded];
//        [strongSelf.scrollView layoutIfNeeded];
//    };
//    // tipView
//    [((AppDelegate *)([UIApplication sharedApplication].delegate)).window addSubview:chooseView];
//    self.chooseSymptomsView = chooseView;
//    [chooseView mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.leading.trailing.top.bottom.equalTo(chooseView.superview);
//    }];
//}

-(void)done:(QMUIButton *)done {
    
    [[LTPHud Instance]showHudLasting:1.5];
    [self.ecgRecord updateSymptoms:^(BOOL succ) {
        
    }];
    
    self.state = ECG_MEA_STA_INIT; // 回到初始
}


-(void)setState:(ECG_MEA_STA)state
{
    _state = state;
    
    switch (_state) {
        case ECG_MEA_STA_INIT: // 初始状态
        {
//            self.symptomSelectView.symptomsArray = nil;
//            self.symptomSelectView.hidden = YES;
            self.resTipLbl.hidden = YES;
            self.hrItem.hidden = YES;
            self.startBtn.selected = NO;
            self.startBtn.hidden = NO;

//            self.startBtn.backgroundColor = MAIN_BLUE;
            self.startBtn.hidden = NO;
            self.doneBtn.hidden = YES;

            self.hrItem.titleLbl.text = nil;
            
            self.topLabel.text = nil;
            self.hrDescLbl.hidden = YES;
            self.hrDescLbl.text = nil;
            
            self.realMeaDrawLineView.hidden = NO;
            self.realGridView.hidden = NO;
            self.hisDrawLineView.hidden = YES;
            
            [self.realMeaDrawLineView reset];
            [self.hisDrawLineView reset];
            [self hideEcgUseDescView]; // 隐藏接触提示
//            [self.measuProgressView setProgress:0 animated:NO];
           
            [self.mainContent layoutIfNeeded];
            [self.view layoutIfNeeded];
            self.infoBtn.hidden = YES;
            
        }
            break;
        case ECG_MEA_STA_WAIT_LEADON:
        {
            // 显示手指提示view
            [self showEcgUseDescView];
            // 重置 定时器 波形数组 画图view
            self.ecgRecord.volArray = [NSMutableArray new];
            [self.hisDrawLineView reset];
//            [self stopTimer];
            
        }
            break;
        case ECG_MEA_STA_MEASURING: // 测量中状态
        {
            // 隐藏 leadon view
            [self hideEcgUseDescView];
            // 定时器启动
//            [self startTimer];
//            self.measuProgressView.hidden = NO;
            
            self.topLabel.text = _L(L_ECG_READY_MEASURE);//[NSString stringWithFormat:@"%ld %@", ECG_MESURING_DURA_SECONDS, @"s"];
            self.hrItem.hidden = NO;
            self.hrDescLbl.hidden = NO;

            self.startBtn.selected = YES;
            self.startBtn.hidden = YES;
//            self.startBtn.backgroundColor = BUTTON_RED;
            
            self.hrItem.titleLbl.text = [NSString stringWithFormat:@"%@ %@", NONE_VALUE, _L(L_UNIT_HR)];
            self.hrDescLbl.text = [NSString stringWithFormat:_L(L_NOTE_CANNOT_DETEC_HRATTACK), [ConfigModel appName]];
            self.resTipLbl.hidden = YES;
//            self.symptomSelectView.hidden = YES;
            self.hrImageView.hidden = NO;
        }
            break;
        case ECG_MEA_STA_DONE: // 等待用户done状态
        {
//            self.startBtn.selected = NO;
//            self.startBtn.backgroundColor = MAIN_BLUE;
            self.resTipLbl.hidden = NO;
//            self.symptomSelectView.hidden = NO;
            self.hrImageView.hidden = NO;
            
            // 保存
            [self.ecgRecord insert:^(BOOL succ) {
                
            }];
            self.startBtn.hidden = YES;
            self.doneBtn.hidden = NO;
            
            self.realMeaDrawLineView.hidden = YES;
            self.realGridView.hidden = YES;
            self.hisDrawLineView.hidden = NO;
            self.hisDrawLineView.drawLineView.direction = self.ecgRecord.wearHand;

            [self.hisDrawLineView drawAllData:self.ecgRecord.volArray];
            self.infoBtn.hidden = NO;
            
        }
            break;
        case ECG_MEA_STA_ERROR:
        {
            [self stopEcgMeasure];
        }
            break;
            
        default:
            break;
    }
}


#pragma  mark --蓝牙代理
- (void)srBleDeviceBatteryLevel:(NSInteger)batteryLevel IsCharging:(BOOL)isCharging {
    
   
    
    if (self.state == ECG_MEA_STA_INIT && isCharging) {
        self.chargeTipLbl.hidden = NO;
    } else {
        self.chargeTipLbl.hidden = YES;
    }
}

- (void)srBleDeviceDidReadyForReadAndWrite:(nonnull SRBLeService *)service {
    
}

- (void)srBleDeviceInfo:(nonnull SRDeviceInfo *)devInfo {
    
}

- (void)srBleDeviceRealtimeSteps:(nonnull NSNumber *)steps IsDeviceFix:(BOOL)isDeviceFixed {
    
}

- (void)srBleDeviceRealtimeTemperature:(nonnull NSNumber *)temperature {
    
}

- (void)srBleDidConnectPeripheral:(nonnull SRBLeService *)service {
    self.startBtn.enabled = YES;
   
}

- (void)srBleDidDisconnectPeripheral:(nonnull SRBLeService *)service {
    
    
    self.chargeTipLbl.hidden = YES;
    
    if (self.state == ECG_MEA_STA_WAIT_LEADON
        || self.state == ECG_MEA_STA_MEASURING) {
        WEAK_SELF
        self.state = ECG_MEA_STA_ERROR;
        [self showAlertWarningWithTitle:_L(L_TIPS) Msg:_L(L_TIPS_ECG_BLE_DISC) btnOk:_L(L_SURE) OkBLk:^{
            STRONG_SELF
            
            strongSelf.state = ECG_MEA_STA_INIT;
            
        } CancelBtn:nil CancelBlk:nil Compelete:nil];
    }
    
    self.startBtn.selected = NO;
    self.startBtn.hidden = NO;
//    self.startBtn.backgroundColor = MAIN_BLUE;

    self.startBtn.enabled = NO;
    
    
}

-(void)srBleEcgEcgLeadOn:(BOOL)leadOn
{
    // 手指检测 yes = 手指接触  no = 手指松开
    DebugNSLog(@"手指接触 %d", leadOn);
    if (self.state == ECG_MEA_STA_WAIT_LEADON) {
        DebugNSLog(@"手指  ECG_MEA_STA_WAIT_LEADON %d", leadOn);
        // 初始状态
        if (leadOn == YES) {
            // 进入测量中状态
            self.state = ECG_MEA_STA_MEASURING;
        }
        return;
    }
    
    if (self.state == ECG_MEA_STA_MEASURING) {
        DebugNSLog(@"手指  ECG_MEA_STA_MEASURING %d", leadOn);

        // 测量中的断开
        if (leadOn == NO) {
            // 进入 等待leanon
            self.state = ECG_MEA_STA_WAIT_LEADON;
        }
        
    }
    
}



- (void)srBleHistoryDataCount:(NSInteger)count {
    
}

- (void)srBleHistoryDataTimeout {
    
}



- (void)srBleMeasureDuration:(NSInteger)seconds {
    
}

- (void)srBleOEMAuthResult:(BOOL)authSucceddful {
    
}



- (void)srBleSN:(nonnull NSString *)sn SnData:(nonnull NSData *)snData {
    
}

- (void)srBleSOShappen {
    
}

- (void)srBlesSOSData:(float)temperature HeartRate:(NSInteger)hr BloodOxygen:(NSInteger)bloodOxygen {
    
}

/// 回调ecg波形
-(void)srBleEcgWave:(SrEcgData *)ecgObj
{
    if (![LTSRingSDK instance].ecgParamObj.isRowWave) {
        // trans
        NSMutableArray <NSNumber *> *volArray = [NSMutableArray new];
        [ecgObj.ecgArray enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSNumber *transVol = @([[LTSRingSDK instance].ecgParamObj transWaveToVol:obj.floatValue]);
            
            [volArray addObject:transVol];
//            DebugNSLog(@"ecg 波 %@, vol %@",  obj, transVol);
        }];
        
        if (!self.ecgRecord.volArray.count) { // 过滤开头的0值
            BOOL canAdd = YES;//NO;
//            for (NSNumber * vol in volArray) {
//                if (vol.floatValue != 0) {
//                    canAdd = YES;
//                    break;
//                }
//                
//            }
            
            if (canAdd) {
                [self.realMeaDrawLineView updateValues:volArray];
                
                if (self.ecgResultArray.lastObject.alive) {
                    [self.ecgRecord.volArray addObjectsFromArray:volArray];

                    // 剩余几秒
                    int restSeconds = (ECG_MESURING_DURA_SECONDS * 512 - (int)self.ecgRecord.volArray.count) / 512;
                    if (restSeconds < 0) {
                        restSeconds = 0;
                    }
                    self.topLabel.text = [NSString stringWithFormat:@"%@%d%@", _L(L_ESTIMATED_REMAIN), restSeconds, @"s"];
                    
                }
            }
            return;
        }
        
        if (self.ecgRecord.volArray.count < ECG_MESURING_DURA_SECONDS * 512) {
            if (self.state == ECG_MEA_STA_MEASURING) { // 避免leadon = off时存0值
                // 测量数据不够
                [self.realMeaDrawLineView updateValues:volArray];
                [self.ecgRecord.volArray addObjectsFromArray:volArray];

                int restSeconds = (ECG_MESURING_DURA_SECONDS * 512 - (int)self.ecgRecord.volArray.count) / 512;
                if (restSeconds < 0) {
                    restSeconds = 0;
                }
//                DebugNSLog(@"剩余 %d 秒", restSeconds);
                self.topLabel.text = [NSString stringWithFormat:@"%@%d%@", _L(L_ESTIMATED_REMAIN), restSeconds, @"s"];
            }
           

        } else {
            if (self.state != ECG_MEA_STA_DONE) {
                DebugNSLog(@"准备停止, 数组数量 %lu", self.ecgRecord.volArray.count);
                // 切换为停止状态
                [self stopEcgMeasure]; //停止测量
                self.state = ECG_MEA_STA_DONE;
            }
        }

    }
    
    if ([LTSRingSDK instance].ecgParamObj.isRowWave){
        
        [self.realMeaDrawLineView updateValues:ecgObj.ecgArray];
        
    }
}

// ecg+ ppg混合
-(void)srBleEcgAndPPgWave:(SrEcgData *)ecgPpgObj
{
   
}

// 回调ecg计算结果
-(void)srBleEcgAlgorithmResult:(SrEcgAlgorithmResults *)ecgResult
{
    
    [self.ecgResultArray addObject:ecgResult];
  
//    DebugNSLog(@"ecg 用户连接: %d", ecgResult.present );
    self.hrItem.titleLbl.text = [NSString stringWithFormat:@"%d %@", ecgResult.heartRate, _L(L_UNIT_HR)];
    if (ecgResult.avgHeartrate > 40 && ecgResult.avgHeartrate < 200) {
        self.ecgRecord.avgHeartRate =  @(ecgResult.avgHeartrate);
    }
    
//    if (ecgResult.alive && self.state == ECG_MEA_STA_MEASURING) {
        //检测到活体生物 开始采集数据 计时
//        self.topLabel.text = nil;
//    }
    
    
//    [self printEcgResult:ecgResult];
    
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.scrollView.contentSize = CGSizeMake(self.scrollView.bounds.size.width, CGRectGetMaxY(self.mainContent.frame));

}

-(void)handChange:(UISegmentedControl *)seg
{
    if (seg.selectedSegmentIndex == 0) {
        self.wearHand = LEFT_HAND;
    }
    
    if (seg.selectedSegmentIndex == 1) {
        self.wearHand = RIGHT_HAND;
    }
    
}

#pragma mark --lazy
- (QMUIButton *)startBtn
{
    if (!_startBtn) {
        _startBtn = [[QMUIButton alloc]init];
        _startBtn.backgroundColor = MAIN_BLUE;
        
        _startBtn.cornerRadius = ITEM_CORNOR_RADIUS;
        [_startBtn setTitle:_L(L_START_MEASURE) forState:UIControlStateNormal];
//        [_startBtn setTitle:_L(L_EARLY_END) forState:UIControlStateSelected];

        [_startBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_startBtn addTarget:self action:@selector(startEcg:) forControlEvents:UIControlEventTouchUpInside];
        _startBtn.enabled = NO; // 初始不可用
    }
    return _startBtn;
}

-(QMUIButton *)doneBtn
{
    //
    if (!_doneBtn) {
        _doneBtn = [[QMUIButton alloc]init];
        _doneBtn.backgroundColor = MAIN_BLUE;
        
        _doneBtn.cornerRadius = ITEM_CORNOR_RADIUS;
        [_doneBtn setTitle:_L(L_TXT_FINISH) forState:UIControlStateNormal];

        [_doneBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_doneBtn addTarget:self action:@selector(done:) forControlEvents:UIControlEventTouchUpInside];
        _doneBtn.hidden = YES;
    }
    return _doneBtn;
}

-(LTRingEcgDrawLineView *)realMeaDrawLineView
{
    if (!_realMeaDrawLineView) {
        LTRingEcgDrawLineView *lineView = [[LTRingEcgDrawLineView alloc]init];
//        [self.view addSubview:lineView];
        lineView.backgroundColor = UIColor.clearColor;//ECG_BACKGROUND_COLOR_DEFAULT;
        //suggest to use HORIZONTAL_SPEED_DEFAULT and VERTIAL_GAIN_DEFAULT
        
        NSNumber *spType = @(HORIZONTAL_SPEED_DEFAULT);
        NSNumber *ygainType = @(VERTIAL_GAIN_DEFAULT);
        
        lineView.direction = self.wearHand;//[AccountCenter instance].currentAccount.otherInfo.wearHand.intValue;
        
        [lineView setHorizonalSpeed:spType.unsignedIntValue VertialGain:ygainType.unsignedIntValue];
        lineView.ecgLineColor = UIColor.redColor;
        _realMeaDrawLineView = lineView;
    }
    
    return _realMeaDrawLineView;
}

//-(UILabel *)heartRateLbl
//{
//    if (!_heartRateLbl)
//    {
//        _heartRateLbl = [UILabel new];
//        _heartRateLbl.font = [UIFont fontWithName:FONT_ARIAL_BOLD size:17];
//    }
//    return _heartRateLbl;
//}

-(UILabel *)hrDescLbl
{
    if (!_hrDescLbl)
    {
        _hrDescLbl = [UILabel new];
        _hrDescLbl.numberOfLines = 0;
        _hrDescLbl.adjustsFontSizeToFitWidth = YES;
        _hrDescLbl.font = [UIFont fontWithName:FONT_ARIAL_BOLD size:16];
    }
    return _hrDescLbl;
}



-(ImgTitleItem *)hrItem
{
    if (!_hrItem) {
        _hrItem = [[ImgTitleItem alloc]init];
        _hrItem.imageView.image = [UIImage imageNamed:@"ecg_hr"];
        _hrItem.titleLbl.font = [UIFont fontWithName:FONT_ARIAL_BOLD size:17];
        
    }
    return _hrItem;
}

-(UILabel *)resTipLbl
{
    if (!_resTipLbl) {
        _resTipLbl = [UILabel new];
        _resTipLbl.textColor = UIColor.lightGrayColor;
        _resTipLbl.font = [UIFont systemFontOfSize:14];
        _resTipLbl.numberOfLines = 0;
        _resTipLbl.adjustsFontSizeToFitWidth = YES;
        _resTipLbl.text = _L(L_ECG_RES_TIP);
    }
    
    return _resTipLbl;
}

// 充电中提示
-(UILabel *)chargeTipLbl
{
    if (!_chargeTipLbl) {
        _chargeTipLbl = [UILabel new];
        _chargeTipLbl.font = [UIFont systemFontOfSize:15];
        _chargeTipLbl.numberOfLines = 0;
        _chargeTipLbl.adjustsFontSizeToFitWidth = YES;
        _chargeTipLbl.text = _L(L_ECG_MEA_HARGE_TIP);
        _chargeTipLbl.textColor = UIColor.redColor;
    }
    
    return _chargeTipLbl;
}

//-(SymptomsBtnView *)symptomSelectView
//{
//    if (!_symptomSelectView) {
//        _symptomSelectView = [[SymptomsBtnView alloc]init];
//        WEAK_SELF
//        _symptomSelectView.clickBlk = ^{
//            STRONG_SELF
//            [strongSelf showEcgChooseSymptomsView];
//        };
//    }
//    return _symptomSelectView;
//}

-(LTRingEcgDrawHistoryView *)hisDrawLineView
{
    if (!_hisDrawLineView) {
        _hisDrawLineView = [[LTRingEcgDrawHistoryView alloc]init];
       
        NSNumber *spType = @(HORIZONTAL_SPEED_DEFAULT);
        NSNumber *ygainType = @(VERTIAL_GAIN_DEFAULT);
        
        _hisDrawLineView.drawLineView.direction = self.wearHand;
        [_hisDrawLineView setHorizonalSpeed:spType.unsignedIntValue VertialGain:ygainType.unsignedIntValue];
        _hisDrawLineView.ecgLineColor = UIColor.redColor;
    }
    return _hisDrawLineView;
}



-(UIScrollView *)scrollView
{
    if(!_scrollView) {
        _scrollView = [UIScrollView new];
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    return _scrollView;
}

-(UIButton *)infoBtn
{
    if (!_infoBtn) {
        
        UIButton *infoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [infoBtn setImage:[UIImage imageNamed:@"info"] forState:UIControlStateNormal];
        [infoBtn addTarget:self action:@selector(gotoShowInfo:) forControlEvents:UIControlEventTouchUpInside];
        _infoBtn = infoBtn;
    }
    return _infoBtn;
}

-(UISegmentedControl *)handSegment
{
    if (!_handSegment) {
        _handSegment = [[UISegmentedControl alloc]initWithItems:@[@"Left hand", @"Right Hand"]];
        _handSegment.selectedSegmentIndex = 0;
        [_handSegment addTarget:self action:@selector(handChange:) forControlEvents:UIControlEventValueChanged];
    }
    return _handSegment;
}

@end


// 测试的函数
@implementation EcgMeasureVc (Test)

-(void)printEcgResult:(SrEcgAlgorithmResults *)ecgResult
{
    
#if DEBUG == 0
    return;
#endif
    
    NSString *signalQualityDesc = @"";
    switch (ecgResult.ecgSq) {
        case ECG_SQ_NO_SIGNAL:
        {
            signalQualityDesc = @"Signal: This state indicates that the ECG signal is not present. That is, the user is not connected to an ECG device.";//@"信号:该状态表示心电图信号不存在。即用户未连接到ECG 设备。";
        }
            break;
        case ECG_SQ_TOO_MUSH_NOISE_NO_HR:
        {
            signalQualityDesc = @"Signal:The user is connected to an ECG device, but the ECG signal quality is poor and the heartbeat cannot be determined. This may be due to excessive noise on the ECG signal. No ECG algorithm can operate at this level of signal quality.";// 该状态表示用户已连接到心电图设备，但心电图信号质量不佳，无法确定心跳。这可能是由于心电图信号上的噪音过多。没有任何心电图算法可以在这种信号质量水平下运行。
        }
            break;
        case ECG_SQ_NOISE:
        {
            signalQualityDesc = @"Signal:This status indicates that the heartbeat can be determined in the ECG signal, but a large amount of noise is detected in the signal. In this kind of User authentication/identification is not possible at signal quality level.";// 信号:该状态表示在心电图信号中可以确定心跳，但是信号中检测到了大量的噪音。在这种信号质量水平下无法进行用户验证/识别。
        }
            break;
        case ECG_SQ_GOOD:
        {
            signalQualityDesc = @"Signal:The signal is very good.";// 该状态表示心跳可以在心电图信号中确定，并且该信号足够清晰，没有噪音干扰，适合所有心电图算法运行
        }
            break;
        default:
            break;
    }
    
    NSString *heartRateStr = @"";
    if (ecgResult.heartRate > 1 && ecgResult.heartRate < 254) {
//        DebugNSLog(@"ecg heartrate : %d", ecgResult.heartRate);
        heartRateStr = [NSString stringWithFormat:@"\r\n%@:%d \r\n",  @"heart rate", ecgResult.heartRate];
    }
  
    NSString *heartRateCheckResString = @"";
    switch (ecgResult.arrhythmia) {
        case Arrhythmia_NO_FINNISH:
        {
            heartRateCheckResString = @"The arrhythmia test is incomplete and has no results.";// 心律失常检查未完成，没有结果。
        }
            break;
        case Arrhythmia_NORMAL:
        {
            heartRateCheckResString = @"The arrhythmia test was completed and no abnormal events were found.";//心律失常检查完成，未发现异常事件。
        }
            break;
        case Arrhythmia_NOT_ENOUGH_DATA:
        {
            heartRateCheckResString = @"Arrhythmia workup completed, no good enough EKG collected to make any decisions"; // 心律失常检查完成，没有收集到足够好的心电图来做出任何决定
        }
            break;
        case Arrhythmia_AFib:
        {
            heartRateCheckResString = @"Arrhythmia test completed, atrial fibrillation (AFib) detected";//心律失常检查完成，检测到心房颤动（AFib）
        }
            break;
        case Arrhythmia_Bradycardia:
        {
            heartRateCheckResString = @"Arrhythmia workup was completed and bradycardia was detected."; // 心律失常检查完成，检测到心动过缓。
        }
            break;
        case Arrhythmia_Tachycardia:
        {
            heartRateCheckResString = @"心动过速";//@"Arrhythmia workup was completed and tachycardia was detected."; // 心动过速
        }
            break;
        case Arrhythmia_Abnormal_unknowReason:
        {
            heartRateCheckResString = @"The arrhythmia test was completed and there were abnormalities, but bradycardia, atrial fibrillation, and tachycardia could not be confirmed.";// 心律失常检查完成，有异常，但无法确认心动过缓、心房颤动、心动过速。
        }
            break;
            
        default:
            break;
    }
    
    heartRateCheckResString = [heartRateCheckResString stringByAppendingFormat:@" arrhythmia:%lu", (unsigned long)ecgResult.arrhythmia];
    
    NSMutableString *errorReason = [NSMutableString new];
    if (ecgResult.low_amplitude) {
        [errorReason appendString:@"The ECG signal amplitude is very low, please make sure the contacts are clean and try again."];// 心电图信号振幅很低，请确保接触面清洁，然后重试。
    }
    if (ecgResult.significant_noise) {
        [errorReason appendString:@"The ECG signal has noticeable noise, please make sure you are not holding the device too tightly and try again。"];// 心电图信号有明显的噪音，请确保设备没有握得太紧，然后重试。
    }
    if (ecgResult.not_enough_data) {
        [errorReason appendString:@"Not enough data."];// 没有足够的数据.
    }
    if (ecgResult.unstable_signal) {
        [errorReason appendString:@"The ECG signal seems unstable"];// 心电图信号似乎不稳定
    }
    
    NSString *stressString = [NSString stringWithFormat:@"stress:%d", ecgResult.stress];
    
    
    NSString *rmssdString = [NSString stringWithFormat:@"RMSSD: %u", ecgResult.rmssd];
    NSString *sdnnString = [NSString stringWithFormat:@"SDNN: %u", ecgResult.sdnn];
    NSString *bmrStr = [NSString stringWithFormat:@"BMR: %u %@", ecgResult.bmr, @"kcal/min"];
    NSString *Functionalenergyconsumption = [NSString stringWithFormat:@"%@: %u  %@", @"功能性消耗", ecgResult.activeCal, @"kcal/min"];
    
    NSMutableString *totalString = [NSMutableString new];
    [totalString appendString: signalQualityDesc];

    [totalString appendString: heartRateStr];
    [totalString appendString: heartRateCheckResString];
    [totalString appendString: errorReason];
    [totalString appendString: @"\r\n"];
    [totalString appendString: stressString];
    [totalString appendString: @"\r\n"];

    [totalString appendString: rmssdString];
    [totalString appendString: @"\r\n"];
    [totalString appendString: sdnnString];
    [totalString appendString: @"\r\n"];
    [totalString appendString: bmrStr];
    [totalString appendString: @"\r\n"];
    [totalString appendString: Functionalenergyconsumption];
    [totalString appendString: @"\r\n"];

    DebugNSLog(@"心电结果: %@", totalString);
}

-(SepLineView *)creatSepLine {
    SepLineView *sep = [[SepLineView alloc]init];
    sep.lineColor = SEPLINE_COLOR(0.7);
    sep.isDash = YES;
    return sep;
}



@end
